// pages/trade/trade.js
// 模拟数据
const mockStocks = [
  { code: '600000', name: '浦发银行', price: 10.25, change: 0.52, open: 10.10, high: 10.30, low: 10.05, volume: 150000 },
  { code: '000001', name: '平安银行', price: 15.30, change: -1.23, open: 15.40, high: 15.45, low: 15.10, volume: 220000 },
  { code: '601318', name: '中国平安', price: 48.75, change: 2.15, open: 48.00, high: 48.90, low: 47.80, volume: 350000 },
  { code: '600519', name: '贵州茅台', price: 1720.50, change: 1.85, open: 1710.00, high: 1725.00, low: 1705.00, volume: 50000 }
];

// 添加股票历史数据
const stockHistoricalData = {
  '600000': generateHistoricalData(10.10, 30),
  '000001': generateHistoricalData(15.40, 30),
  '601318': generateHistoricalData(48.00, 30),
  '600519': generateHistoricalData(1710.00, 30)
};

// 生成历史数据的函数
function generateHistoricalData(startPrice, days) {
  const data = [];
  let currentPrice = startPrice;
  
  for (let i = days; i >= 0; i--) {
    // 生成随机波动
    const changePercent = (Math.random() - 0.5) * 0.04; // 日涨跌幅在-2%到2%之间
    const newPrice = currentPrice * (1 + changePercent);
    
    // 计算最高价和最低价
    const high = Math.max(currentPrice, newPrice) * (1 + Math.random() * 0.01);
    const low = Math.min(currentPrice, newPrice) * (1 - Math.random() * 0.01);
    
    // 成交量
    const volume = Math.floor(Math.random() * 500000) + 100000;
    
    data.push({
      date: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      open: currentPrice,
      close: newPrice,
      high: high,
      low: low,
      volume: volume
    });
    
    currentPrice = newPrice;
  }
  
  return data;
}

// 用户账户数据
let account = {
  balance: 1000000,
  positions: []
};

Page({
  data: {
    stockData: [],
    stockCode: '',
    tradeType: 'buy',
    priceType: 'market',
    limitPrice: '',
    tradeAmount: '',
    showKLine: false,
    kLineData: {
      name: '',
      code: '',
      data: []
    }
  },

  onLoad() {
    this.renderStockTable();
  },

  renderStockTable() {
    const stockData = mockStocks.map(stock => {
      return {
        code: stock.code,
        name: stock.name,
        price: stock.price.toFixed(2),
        change: stock.change.toFixed(2),
        changeClass: stock.change >= 0 ? 'text-red-500' : 'text-green-500'
      };
    });

    this.setData({
      stockData: stockData
    });
  },

  onTradeBtnTap(e) {
    const code = e.currentTarget.dataset.code;
    this.setData({
      stockCode: code
    });
  },

  onRefresh() {
    this.renderStockTable();
  },

  onStockCodeChange(e) {
    this.setData({
      stockCode: e.detail.value
    });
  },

  onTradeTypeChange(e) {
    this.setData({
      tradeType: e.detail.value
    });
  },

  onPriceTypeChange(e) {
    this.setData({
      priceType: e.detail.value
    });
  },

  onLimitPriceChange(e) {
    this.setData({
      limitPrice: e.detail.value
    });
  },

  onTradeAmountChange(e) {
    this.setData({
      tradeAmount: e.detail.value
    });
  },

  onSubmitTrade(e) {
    const { stockCode, tradeType, priceType, limitPrice, tradeAmount } = this.data;
    
    if (!stockCode || !tradeAmount) {
      wx.showToast({
        title: '请填写完整交易信息',
        icon: 'none'
      });
      return;
    }

    const amount = parseInt(tradeAmount);
    if (isNaN(amount) || amount <= 0) {
      wx.showToast({
        title: '交易数量必须为正整数',
        icon: 'none'
      });
      return;
    }

    const stock = mockStocks.find(s => s.code === stockCode);
    if (!stock) {
      wx.showToast({
        title: '未找到该股票',
        icon: 'none'
      });
      return;
    }

    const price = priceType === 'market' ? stock.price : parseFloat(limitPrice);
    if (priceType === 'limit' && (isNaN(price) || price <= 0)) {
      wx.showToast({
        title: '请填写正确的委托价格',
        icon: 'none'
      });
      return;
    }

    if (tradeType === 'buy') {
      // 买入逻辑
      const cost = price * amount;
      if (cost > account.balance) {
        wx.showToast({
          title: '可用资金不足',
          icon: 'none'
        });
        return;
      }

      account.balance -= cost;
      const existingPos = account.positions.find(p => p.code === stockCode);
      if (existingPos) {
        existingPos.amount += amount;
        existingPos.cost = ((existingPos.cost * existingPos.amount) + cost) / (existingPos.amount + amount);
      } else {
        account.positions.push({
          code: stockCode,
          name: stock.name,
          amount: amount,
          cost: price,
          buyDate: new Date().toISOString()
        });
      }
    } else {
      // 卖出逻辑
      const position = account.positions.find(p => p.code === stockCode);
      if (!position || position.amount < amount) {
        wx.showToast({
          title: '持仓不足',
          icon: 'none'
        });
        return;
      }

      account.balance += price * amount;
      position.amount -= amount;

      if (position.amount === 0) {
        account.positions = account.positions.filter(p => p.code !== stockCode);
      }
    }

    // 更新账户信息
    this.updateAccountInfo();
    
    wx.showToast({
      title: `委托成功：${tradeType === 'buy' ? '买入' : '卖出'} ${stock.name} ${amount}股`,
      icon: 'success'
    });
    
    // 重置表单
    this.setData({
      stockCode: '',
      tradeAmount: '',
      limitPrice: ''
    });
  },

  updateAccountInfo() {
    const app = getApp();
    if (app.updateAccountInfo) {
      app.updateAccountInfo();
    }
  },

  onViewKLine(e) {
    const code = e.currentTarget.dataset.code;
    const stock = mockStocks.find(s => s.code === code);
    
    if (!stock) return;
    
    this.setData({
      showKLine: true,
      kLineData: {
        name: stock.name,
        code: stock.code,
        data: stockHistoricalData[code] || []
      }
    });
  },

  onCloseKLine() {
    this.setData({
      showKLine: false
    });
  }
});